package jsoniters

import (
	"fmt"
	jsoniter "github.com/json-iterator/go"
	"github.com/modern-go/reflect2"
	"unsafe"

	"time"
)

type TimeExtension struct {
	jsoniter.DummyExtension
}

func (e *TimeExtension) CreateEncoder(typ reflect2.Type) jsoniter.ValEncoder {
	if typ == reflect2.TypeOf(time.Time{}) {
		return &timeEncoder{}
	}
	return nil
}

func (e *TimeExtension) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {
	if typ == reflect2.TypeOf(time.Time{}) {
		return &timeDecoder{}
	}
	return nil
}

type timeEncoder struct{}

func (e *timeEncoder) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
	t := *(*time.Time)(ptr)
	stream.WriteString(t.Format(YYYY_MM_DD_HH_MM_SS))
}

func (e *timeEncoder) IsEmpty(ptr unsafe.Pointer) bool {
	t := *(*time.Time)(ptr)
	return t.IsZero()
}

type timeDecoder struct{}

func (d *timeDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
	str := iter.ReadString()
	t, err := time.Parse(YYYY_MM_DD_HH_MM_SS, str)
	if err != nil {
		iter.ReportError("decode time", err.Error())
		return
	}
	*(*time.Time)(ptr) = t
}

type upperStringExtension struct {
	jsoniter.DummyExtension
}

func (e *upperStringExtension) DecorateDecoder(typ reflect2.Type, decoder jsoniter.ValDecoder) jsoniter.ValDecoder {

	return decoder
}

func RunDecoderExtension() {

	var json = jsoniter.Config{
		EscapeHTML: true,
	}.Froze()

	// 注册自定义解码器
	json.RegisterExtension(&upperStringExtension{})
	json.RegisterExtension(&TimeExtension{})

	data := []byte(`{"name":"john doe","age":30}`)

	var p Person
	err := json.Unmarshal(data, &p)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Printf("%+v\n", p) // 输出: {Name:JOHN DOE Age:30}
}
